# encoding: UTF-8

"""
json 配置 tree

"""

import os,re 
import logging
 
from collections import OrderedDict

import json
 

def demo(cfg_file='cfg.json'):
    """ 根据配置返回 
    一个json的数据库操作api"""
    cfg = gm.load_cfg(cfg_file)
    return JosnApi(cfg['db'],True)



class gm():
    """  静态全局类
        存放一些参数变量，避免全局冲突
    """
    conf = {}  # 配置
    pid = -1  # 进程id
    thre = {}  # 线程池
    one = -1  # 首次运行
    res = {}  # 资源

    @classmethod  # //静态方法
    def load_cfg(cls, json_file, path=None):
        """ 读取一个配置文件
        """
        if not path:
            path = cls.get_pwd()
            json_file = os.path.join(path, json_file)
        try:
            # //配置载入 配置与属性隔离
            with open(json_file, encoding="utf-8") as f:
                setting_dict = json.load(f)
        except Exception as e:
            # logger.error('读取配置文件%s错误%s' % (json_file, e))
            raise Exception('读取配置文件%s错误%s' % (json_file, e))
        return setting_dict

    @classmethod  # //静态方法
    def get_pwd(cls):
        """  获取脚本目录 """
        try:
            FILE_PATH = os.path.dirname(os.path.realpath(__file__))  # //当前路径
        except Exception as e:
            FILE_PATH = os.getcwd()
        return FILE_PATH



class CfgJson():

    def __init__(self, pwd='' ):
        """  初始化 """
        self.pwd = pwd
        self.jnls = [] #[{}]

    def read(self,fileName):
        """ 读取配置文件 """
        # json 内容读取
        with open(fileName,'r',encoding='utf-8') as f:
            try:
                content = f.read()
            except Exception as e:
                print("err",e,fileName) 
    
        return   content

    def write(self,fileName,content):
        """ 写取配置文件 """
        # json 内容读取
        with open(fileName,'w',encoding='utf-8') as f:
            try:
                content = f.write(content)
            except Exception as e:
                print("err",e,fileName) 
    
        return   fileName

        
    def recu(self,d,m=10):
        """ 递归调用自己扫描目录 
            d:str 目录字符串
            m:int 扫描深度
        """
        self.jnls = [] #[{}]
        self._recu(d,self.jnls,0,m)
        return self.jnls


    def _recu(self,d,jnls,i=0,m=10):
        """ 递归调用自己扫描目录  
            d:str 目录字符串
            jnls:list  符合条件的收集箱子
            i:int 目录深度  5层一下不处理
            m:int 扫描深度
        """
        # 深度判断
        if i>m:
            return 
        dis  = os.listdir(d) 
        for di in dis :
            ## 名字判断
            if ( di[0]=='.' or di[0:2]== '__' ):
                continue
            # 目录判断
            fileName = os.path.join(d,di)
            if os.path.isdir(fileName):            
                self._recu(os.path.join(d,di),jnls,i+1,m)#递归
                continue
            # 类型判断
            if (   di[-5:].lower()!='.json'):
                continue
            # json 内容判断
            with open(fileName,'r',encoding='utf-8') as f:
                try:
                    result=json.load(f)
                    comment = result['#comment'] #//特征
                    jnls.append({"path":os.path.join(d,di),"file":di,"comment":comment })
                except Exception as e:
                    logging.error('不合适文件{}错误{}'.format(fileName,e))

                    
                    

if __name__ == "__main__":
    # 第一步，创建一个日志器
    # create logger
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logging.getLogger('mylog')
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    #gm.conf = gm.load_cfg('web.json')
    # //----- 长时间运行

    try:
        # --循环
        cj = CfgJson()
        print(cj.recu(os.getcwd()))
    except KeyboardInterrupt as e:
        print(u" 用户手动停止了web服务 ")
